import { fileURLToPath, URL } from "node:url";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import { viteMockServe } from "vite-plugin-mock";
import legacy from "@vitejs/plugin-legacy";

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd());
  return {
    plugins: [
      vue(),
      legacy(),
      viteMockServe({
        enable: true, // 重要：开启 mock 服务（开发环境建议设为 true）
        mockPath: "./src/mock/",
        localEnabled: command === "serve",
        prodEnabled: false, // 生产环境不启用mock
        logger: true, // 启用日志
        supportTs: true, // 支持typescript
        watchFiles: true, // 监听文件变化
        injectCode: `
          import { setupDevMockServer } from './src/mock/dev/api';
          setupDevMockServer();
        `,
        ignore: [], // 忽略的文件
        configPath: "/mock", // mock文件配置目录
      }),
    ],
    build: {
      // 其他配置
      outDir: env.VITE_OUTPUTDIR,
    },
    resolve: {
      extensions: [".js", ".jsx", ".ts", ".tsx", ".json", ".vue"],
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    css: {
      // 配置 CSS 预处理器
      preprocessorOptions: {
        scss: {
          api: "modern-compiler", // 修改api调用方式
          // 这里添加sass-loader的特定配置
          additionalData: `@use "@/assets/style/global_variables.scss" as *;`,
        },
      },
    },
    server: {
      proxy: {
        "/api": {
          target: env.VITE_APP_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
          // 排除mock请求，让vite-plugin-mock处理
          bypass: (req, res, options) => {
            if (
              req.url.startsWith("/mock/dev/login") ||
              req.url.startsWith("/mock/dev/userInfo")
            ) {
              return false;
            }
          },
        },
      },
    },
  };
});
